#include <iot_errno.h>
#include <iot_gpio_ex.h>
#include <iot_gpio.h>
#include <cmsis_os2.h>
#include <ohos_init.h>

#define LED_PIN   6

unsigned int  init_led(void)
{
    unsigned int ret;

    ret = IoTGpioInit(LED_PIN);
    if (ret != IOT_SUCCESS)
    {
        printf("IoTGpioInit  ret == %u\n", ret);
        goto _ret ;
    }

    ret = IoTGpioSetFunc(LED_PIN, IOT_GPIO_FUNC_GPIO_6_GPIO);
    if (ret != IOT_SUCCESS)
    {
        printf("IoTGpioSetFunc, ret == %u\n", ret);
        goto _ret ;
    }

    ret = IoTGpioSetDir(LED_PIN, IOT_GPIO_DIR_OUT);
    if (ret != IOT_SUCCESS)
    {
        printf("IoTGpioSetDir, ret == %u\n", ret);
    }
_ret:
    return ret;
}


#define ON  2
#define OFF 3


void control_led(int on_or_off)
{
    unsigned int ret = IOT_SUCCESS;    

    if (on_or_off == ON)
    {
        ret = IoTGpioSetOutputVal(LED_PIN, IOT_GPIO_VALUE1);
    } else if(on_or_off == OFF) {
        ret = IoTGpioSetOutputVal(LED_PIN, IOT_GPIO_VALUE0);
    } else {
        printf("invalid parameter %d\n", on_or_off);
    }
}

//让LED灯闪烁
static int led_task(void)
{
    unsigned int ret = IOT_SUCCESS;
    sleep(10);
    printf("begin init_led\n");
    ret = init_led();
    printf("after init_led, ret = %u\n", ret);

    while (1)
    {
        printf("ON\n");
        control_led(ON);
        sleep(5);
        printf("OFF\n");
        control_led(OFF);
        sleep(2);
    }

    return 0;
}

void led_demo()
{
    osThreadAttr_t attr;

    attr.name = "led_task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024;
    attr.priority = 25;

    if (osThreadNew((osThreadFunc_t)led_task, NULL, &attr) == NULL)
    {
        printf("Falied to create led task!\r\n");
    }
}

APP_FEATURE_INIT(led_demo);